package com.imooc.zkjavaapi;

import org.apache.zookeeper.WatchedEvent;
import org.apache.zookeeper.Watcher;
import org.apache.zookeeper.ZooKeeper;

import java.io.IOException;

/**
 * 连接到Zookeeper服务端，打印连接状态
 */
public class ZKConnect implements Watcher {
    public static final String SERVER_PATH = "127.0.0.1:2181";
    public static final Integer timeout = 5000;

    public static void main(String[] args) throws IOException, InterruptedException {
        /**
         * 客户端和服务端他们是异步连接，连接成功后，客户端会收到watcher通知。
         * connectString: 服务器的IP+端口号，比如127.0.0.1:2128
         * sessionTimeout: 客户端和服务端之间的超时时间，单位毫秒
         * watcher: 监听器，当连接成功后，客户端会收到watcher通知
         */
        ZooKeeper zk = new ZooKeeper(SERVER_PATH, timeout, new ZKConnect());
        System.out.println("客户端开始连接Zookeeper服务端...");
        System.out.println("连接状态：" + zk.getState());
        Thread.sleep(2000); // 等待20秒，观察连接状态变化
        System.out.println("连接状态：" + zk.getState());
    }


    @Override
    public void process(WatchedEvent watchedEvent) {
        System.out.println("收到通知：" + watchedEvent);
    }
}
